import com.mind.jenkins.pipeline.utils.BuildConfig

def call() {
    properties([
            parameters([
                    string(defaultValue: '', description: '', name: 'COMMIT', trim: false),
                    string(defaultValue: 'master', description: '', name: 'BRANCH', trim: false),
            ])
    ])

    dockerNode.javaBuildDocker {
        BuildConfig buildConfig
        boolean isSuccess = false
        try {
            stage('Preparation') {
                //checkout scm
                checkout([
                        $class           : 'GitSCM',
                        branches         : [[name: COMMIT]],
                        userRemoteConfigs: scm.userRemoteConfigs
                ])
            }

            buildConfig = BuildConfig.load(this)
            if (buildConfig == null) {
                throw new Exception("Cannot parse build.yaml")
            }

            String appname = jobUtil.getAppNameFromJob()
            Object setting = buildConfig.getAppSetting(appname)
            if (setting == null) {
                throw new Exception("Cannot find this app from build.yaml")
            }

            Object commitInfo = jobUtil.getCommitInfo()

            // 打包，备用，为了绕过mobius检测，暂时无其他用
            stage('Bundle') {
                echo "Try Bundle: ${appname}@${commitInfo.version}"
                timeout(15) {
                    if (setting.script.matches(/^[^ ]+\.sh$/)) {
                        sh "sh -x ${setting.script}"
                    } else {
                        sh setting.script
                    }
                }
                if (!fileExists(setting.target)) {
                    throw new Exception("Cannot find the build target(${setting.target}).")
                }
            }

            String imageName
            String osskey
            stage('Package') {
                echo "Build docker image..."
                imageName = "im30cr.tencentcloudcr.com/im30/${setting.name}:${commitInfo.version}_${env.BUILD_NUMBER}"
                dockerfile = setting.dockerfile ?: "Dockerfile"
                jobUtil.buildDockerImage(dockerfile, setting.target, "python", imageName)
            }

            stage('Banana') {
                echo "Build success, now tell Banana...  ${params.BRANCH}"

                String archiveType = "tar"
                jobUtil.createBananaBuild(appname, archiveType, setting.target, osskey, imageName, commitInfo, params.BRANCH)
            }
        } finally {
            try {
                isSuccess = currentBuild.result == null || currentBuild.result == 'SUCCESS'
                String branch = params.BRANCH
                String commit = params.COMMIT
                notifyUtil.notifyApp(buildConfig.getNotifyConfig(), jobUtil.getRepoName(), branch, commit, isSuccess)
            } catch (err) {
                echo err.getMessage()
                echo "${buildConfig}"
            }
            deleteDir()
        }
    }
}